$(function () {
    var showContentLoading = function () {
        $('.content-panel .content-panel-loading').removeClass('hidden');
    };
    var hideContentLoading = function () {
        $('.content-panel .content-panel-loading').addClass('hidden');
    };
    // 选择日期
    var format = 'YYYY-MM-DD';
    $('#datePickerInput').daterangepicker({
        'showDropdowns': true,
        'autoApply': true,
        'dateLimit': {
            'months': 7
        },
        'locale': {
            'format': format,
            'applyLabel': lang('date.ensure'),
            'cancelLabel': lang('date.cancel'),
            'daysOfWeek': [
                lang('week.7'),
                lang('week.1'),
                lang('week.2'),
                lang('week.3'),
                lang('week.4'),
                lang('week.5'),
                lang('week.6')
            ],
            'monthNames': [
                lang('month.1'),
                lang('month.2'),
                lang('month.3'),
                lang('month.4'),
                lang('month.5'),
                lang('month.6'),
                lang('month.7'),
                lang('month.8'),
                lang('month.9'),
                lang('month.10'),
                lang('month.11'),
                lang('month.12')
            ],
            'firstDay': 1
        },
        'linkedCalendars': false,
        'parentEl': 'body',
        'startDate': $('#datePicker').find('.start').html(),
        'endDate': $('#datePicker').find('.end').html(),
        'minDate': '2000-01-01',
        'maxDate': '2038-01-01',
        'opens': 'left'
    }, function (start, end, label) {
        $('#datePicker').find('.start').html(start.format(format));
        $('#datePicker').find('.end').html(end.format(format));
        refreshPage(window.pageUrl);
        window.pageLink = 1;
        consumptionTable();
    });
    $('#datePickerContainer').on('click', function () {
        $('#datePickerInput').trigger('focus');
    });
    // 趋势图配置
    var lineConfig = {
        chart: {
            type: 'line'
        },
        title: {
            text: ''
        },
        credits: {
            enabled: false
        },
        xAxis: {
            categories: [],
            labels: {
                step: 1
            }
        },
        yAxis: {
            title: {
                text: ''
            },
            min: 0,
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            pointFormat: '<b>{point.y}</b><br/>',
            valueSuffix: ''
        },
        series: []
    };
    var switchSeries = {};
    var refreshPage = function (url) {
        var startDate = $('#datePicker').find('.start').html();
        var endDate = $('#datePicker').find('.end').html();
        //重新渲染趋势图的x轴
        var startDateObj = getDate(startDate);
        var days = getDate(endDate).getDays(startDateObj);
        lineConfig.xAxis.categories = [];
        for (var i = 0; i <= days; i++) {
            lineConfig.xAxis.categories.push(startDateObj.customDays(i).customFormat());
        }
        if (days > 8) {
            lineConfig.xAxis.labels.step = Math.round(days / 8);
        } else {
            lineConfig.xAxis.labels.step = days;
        }
        var param = {};
        param.hotel = window.currentHotel;
        param.start = startDate;
        param.end = endDate;
        showContentLoading();
        ajaxRequest(url, param, 'post', function (data) {
            var info = data.data;
            // 图表数据
            switchSeries.income = [];
            $.each(info.incomeSeries, function (index, value) {
                switchSeries.income.push(parseFloat(value));
            });
            switchSeries.actualOccupancy = [];
            $.each(info.actualOccupancySeries, function (index, value) {
                switchSeries.actualOccupancy.push(parseInt(value));
            });
            switchSeries.occupancyRate = [];
            $.each(info.occupancyRateSeries, function (index, value) {
                switchSeries.occupancyRate.push(parseInt(value));
            });
            switchSeries.price = [];
            $.each(info.priceSeries, function (index, value) {
                switchSeries.price.push(parseFloat(value));
            });
            switchSeries.notSold = [];
            $.each(info.notSoldSeries, function (index, value) {
                switchSeries.notSold.push(parseInt(value));
            });
            switchSeries.notCheckIn = [];
            // info.notCheckInSeries;
            $.each(info.notCheckInSeries, function (index, value) {
                switchSeries.notCheckIn.push(parseInt(value));
            });
            // 房间表格数据
            var roomInfos = info.roomInfo;
            // 运营总览
            var statisticOverview = $('#statisticOverview');
            statisticOverview.find('span[data-tag="actualOccupancy"]').html(info.actualOccupancy);
            statisticOverview.find('span[data-tag="notCheckIn"]').html(info.notCheckIn);
            statisticOverview.find('span[data-tag="notSold"]').html(info.notSold);
            statisticOverview.find('span[data-tag="occupancyRate"]').html(info.occupancyRate);
            statisticOverview.find('span[data-tag="price"]').html(info.price);
            // 运营总览趋势图
            $('#tabSwitchGroup .btn:first-child').trigger('click');
            // 表格渲染
            refreshTable(roomInfos);
            $('#roomInfoContaienr>.content-panel-header').find('a').attr('href', '/Home/Report/exportRoom?hotel=' + window.currentHotel + '&start=' + $('#datePicker').find('.start').html() + '&end=' + $('#datePicker').find('.end').html() + '&type=' + window.type);
            hideContentLoading();
        }, function (error) {
            if (typeof error.responseJSON == 'undefined') {
                modalAlert(lang('tip.server'));
            } else if (error.responseJSON.status == 203) {
                modalAlert(error.responseJSON.info);
                window.setTimeout(dialogLogin(), 1500);
            } else {
                modalAlert(error.responseJSON.info);
            }
        });
    };
    var tabSwitchChart = $('#tabSwitchChart');
    $('#tabSwitchGroup .btn').on('click', function (e) {
        e.preventDefault();
        var tab = $(this);
        tab.addClass('btn-primary').siblings().removeClass('btn-primary');
        lineConfig.yAxis.title.text = tab.data('units');
        lineConfig.tooltip.valueSuffix = tab.data('suffix');
        lineConfig.series = [{
            name: tab.html(),
            data: switchSeries[tab.data('value')]
        }];
        tabSwitchChart.highcharts(lineConfig);
    });
    var refreshTable = function (roomInfos) {
        var trs = '';
        var templateTypeOriginal = $('#templateRoomTypeReportItem');
        var templateOriginal = $('#templateRoomReportItem');
        var trLineIndex = 0;
        $.each(roomInfos, function (index, roomType) {
            var template = $(templateTypeOriginal.clone().html());
            var roomTotal = roomType.rooms.length;
            if (roomTotal === 0) {
                return true;
            }
            var roomTypeLineIndex = trLineIndex;
            var firstRoom = roomType.rooms.shift();
            template.find('[data-tag="name"]').html(firstRoom.isdelete == 1 ? (firstRoom.name + '<span class="text-accent">('+lang('alreadyDeleted')+')</span>') : firstRoom.name);
            template.find('[data-tag="total"]').html(firstRoom.total);
            template.find('[data-tag="actualOccupancy"]').html(firstRoom.actualOccupancy);
            template.find('[data-tag="occupancyRate"]').html(firstRoom.occupancyRate);
            template.find('[data-tag="price"]').html(firstRoom.price);
            template.find('[data-tag="notSold"]').html(firstRoom.notSold);
            template.find('[data-tag="notCheckIn"]').html(firstRoom.notCheckIn);
            template.find('.roomType').attr('rowspan', roomTotal);
            template.find('[data-tag="roomType"]').html(roomType.isdelete == 1 ? (roomType.name + '<span class="text-accent">('+lang('alreadyDeleted')+')</span>') : roomType.name);
            template.find('.roomTypeStatistic').attr('rowspan', roomTotal);
            template.find('[data-tag="roomTypeTotal"]').html(roomType.total);
            template.find('[data-tag="roomTypeOccupancyRate"]').html(roomType.occupancyRate);
            template.find('[data-tag="roomTypePrice"]').html(roomType.price);
            template.find('.roomReportDetailTrigger').attr('data-type-line', roomTypeLineIndex).attr('data-value', firstRoom.id);
            template.find('.exportRoomReportDetailTrigger').attr('data-value', firstRoom.id);
            trs += template.prop('outerHTML');
            trs += '<tr class="first-tr roomReportDetailLine hidden"><td colspan="8"><div class="roomReportDetail"></div></td></tr>';
            trLineIndex += 2;
            $.each(roomType.rooms, function (index, roomInfo) {
                var template = $(templateOriginal.clone().html());
                template.find('[data-tag="name"]').html(roomInfo.isdelete == 1 ? (roomInfo.name + '<span class="text-accent">('+lang('alreadyDeleted')+')</span>') : roomInfo.name);
                template.find('[data-tag="total"]').html(roomInfo.total);
                template.find('[data-tag="actualOccupancy"]').html(roomInfo.actualOccupancy);
                template.find('[data-tag="occupancyRate"]').html(roomInfo.occupancyRate);
                template.find('[data-tag="price"]').html(roomInfo.price);
                template.find('[data-tag="notSold"]').html(roomInfo.notSold);
                template.find('[data-tag="notCheckIn"]').html(roomInfo.notCheckIn);
                template.find('.roomReportDetailTrigger').attr('data-type-line', roomTypeLineIndex).attr('data-value', roomInfo.id);
                template.find('.exportRoomReportDetailTrigger').attr('data-value', roomInfo.id);
                trs += template.prop('outerHTML');
                trs += '<tr class="first-tr roomReportDetailLine hidden"><td colspan="8"><div class="roomReportDetail"></div></td></tr>';
                trLineIndex += 2;
            });
        });
        $('#roomInfoTbody').html(trs);
    };
    window.pageUrl = '/Home/Report/getRoomReport';
    window.type = 1;
    refreshPage('/Home/Report/getRoomReport');
    $('#room-report').click(function () {
        $(this).addClass('btn-primary');
        $(this).siblings().removeClass('btn-primary');
        refreshPage('/Home/Report/getRoomReport');
        window.pageUrl = '/Home/Report/getRoomReport';
        window.type = 1;
    })
    $('#hour-room-report').click(function () {
        $(this).addClass('btn-primary');
        $(this).siblings().removeClass('btn-primary');
        refreshPage('/Home/Report/getHourRoomReport');
        window.pageUrl = '/Home/Report/getHourRoomReport';
        window.type = 2;
    })
    $('#long-room-report').click(function () {
        $(this).addClass('btn-primary');
        $(this).siblings().removeClass('btn-primary');
        refreshPage('/Home/Report/getLongRoomReport');
        window.pageUrl = '/Home/Report/getLongRoomReport';
        window.type = 3;
    })
    window.roomDetailStatistic = {};
    // 点击导出详细
    $('#roomInfoTbody').on('click', '.exportRoomReportDetailTrigger', function(){
        var currentTrigger = $(this);
        var roomId = currentTrigger.data('value');
        var startDate = $('#datePicker').find('.start').html();
        var endDate = $('#datePicker').find('.end').html();
        window.open('/Home/Order/exportList?hotel=' + window.currentHotel + '&room=' + roomId + '&start=' + startDate + '&end=' + endDate + '&datestatus=checkin&type=' + window.type);
    });
    // 点击详细
    $('#roomInfoTbody').on('click', '.roomReportDetailTrigger', function(){
        var currentTrigger = $(this);
        var roomId = currentTrigger.data('value');
        var spanDiff = 1;
        if (currentTrigger.hasClass('open')) {
            currentTrigger.removeClass('open');
            currentTrigger.parents('tr').next().addClass('hidden');
            spanDiff = -1;
        } else {
            currentTrigger.addClass('open');
            currentTrigger.parents('tr').next().removeClass('hidden');
            if (window.roomDetailStatistic[roomId] === undefined) {
                var startDate = $('#datePicker').find('.start').html();
                var endDate = $('#datePicker').find('.end').html();
                ajaxRequest('/Home/Order/subOrder', {hotel: currentHotel, room: roomId, start: startDate, end: endDate, datestatus: 'checkin', type: window.type}, 'post', function (data) {
                    window.roomDetailStatistic[roomId] = data.data;
                    if (data.data.length === 0) {
                        currentTrigger.parents('tr').next().find('.roomReportDetail').html(lang('noOrder'));
                        return true;
                    }
                    var tableHTMLs = '<table class="table content-panel-table"><thead><tr><td>'+lang("order.enterTime")+'</td><td>'+lang("order.enterman")+'</td><td>'+lang("order.enterLive")+'</td><td>'+lang("order.pay")+'</td><td>'+lang("order.status")+'</td></tr></thead><tbody>';
                    var subOrderInfo;
                    for (var i = 0; i < data.data.length; i++) {
                        subOrderInfo = data.data[i]
                        tableHTMLs += '<tr><td>' + subOrderInfo.createTime.substr(5,11) + '</td><td><div>' + subOrderInfo.name + '</div></td><td>'
                         + getDate(subOrderInfo.startDate).customFormat('MM/dd') +' - '+getDate(subOrderInfo.endDate).customFormat('MM/dd') + '</td><td><div>'
                          + subOrderInfo.price + '</div></td><td><div>' + subOrderInfo.statusName + '</div></td></tr>';
                    }
                    tableHTMLs += '</tbody></table>';
                    currentTrigger.parents('tr').next().find('.roomReportDetail').html(tableHTMLs);
                }, function (error) {
                    if (typeof error.responseJSON == 'undefined') {
                        currentTrigger.parents('tr').next().find('.roomReportDetail').html(lang('tip.server'));
                    } else {
                        currentTrigger.parents('tr').next().find('.roomReportDetail').html(error.responseJSON.info);
                    }
                });
            }
        }
        var roomTypeLineIndex = currentTrigger.data('type-line');
        var roomTypeLine = currentTrigger.parents('tbody').find('.first-tr').eq(roomTypeLineIndex);
        var rowspanNew = parseInt(roomTypeLine.find('.roomType').attr('rowspan')) + spanDiff;
        roomTypeLine.find('.roomType').attr('rowspan', rowspanNew);
        roomTypeLine.find('.roomTypeStatistic').attr('rowspan', rowspanNew);
    });
    
    
    //其他消费
    window.pageLink = 1;
    var refreshPageFooter = function (currentPage, pages, total) {
        currentPage = parseInt(currentPage);
        pages = parseInt(pages);
        total = parseInt(total);
        var pageItems = '';
        for (var i = 1; i <= pages; i++) {
            if (i === currentPage) {
                pageItems += '<li class="active"><a href="javascript:void(0);" data-value="' + i + '">' + i + '</a></li>';
            } else {
                pageItems += '<li><a href="javascript:void(0);" data-value="' + i + '">' + i + '</a></li>';
            }
        }
        $('#consumptionContaienr').find('.pagination').html(pageItems);
        $('#consumptionContaienr').find('.content-panel-pagination-count').html(total);
    };    
    var consumptionTable = function () {
        var startDate = $('#datePicker').find('.start').html();
        var endDate = $('#datePicker').find('.end').html();        
        ajaxRequest('/Home/Report/getOrderCost', {
            "hotel": currentHotel,
            "start":startDate,
            "end":endDate,
            'current':window.pageLink
        }, 'post', function(data) {
            var info = data.data;
            var total = info.itemtotal;
            var pages = info.pagetotal;
            var currentPage = info.current;
            var trs = '';
            var templateTypeOriginal = $('#templateConsumptionTypeItem');
            $.each(info.info, function (index, info) {
                var template = $(templateTypeOriginal.clone().html());
                template.find('[data-tag="name"]').html(info.name);
                template.find('[data-tag="info"]').html(info.room);
                template.find('[data-tag="price"]').html(info.totalPrice);
                template.find('[data-tag="order"]').html(info.status);
                template.find('.consumptionDetailTrigger').attr('data-id',info.orderId);
                template.find('.consumptionDetailDel').attr('data-id',info.orderId);
                trs += template.prop('outerHTML');  
            });
            $('#consumptionTbody').html(trs);
            refreshPageFooter(currentPage, pages, total);            
            
        }, function(error) { 
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });         

    };    
    consumptionTable();
    
    //项目详情
    $('#detailModal').on('show.bs.modal', function(e) {
        var startDate = $('#datePicker').find('.start').html();
        var endDate = $('#datePicker').find('.end').html();  
        var triggerId = $(e.relatedTarget);
        ajaxRequest('/Home/Report/getOrderCostDetail', {
            "hotel": currentHotel,
            "start":startDate,
            "end":endDate,
            'orderId':triggerId.data('id')
        }, 'post', function(data) {
            var info = data.data;
            var detailHTML = '';
            $('#detailListBody').html(''); 
            if(info.length !== 0){
                $.each(info, function (index, item) {
                    var templateDetailMessage = $($('#templateDetailMessage').clone().html());
                    templateDetailMessage.find('.info_name').text(item.noteName);
                    templateDetailMessage.find('.info_time').text(item.noteTime);
                    templateDetailMessage.find('.info_price').text(item.notePrice);
                    templateDetailMessage.find('.pay').text(item.notePay);
                    detailHTML += templateDetailMessage.prop('outerHTML');  
                }); 
                $('#detailListBody').append(detailHTML);
                $('#no_detailListBody').addClass('hidden');
                $('#detailListBody').removeClass('hidden'); 
            }else{
                $('#detailListBody').addClass('hidden');
                $('#no_detailListBody').removeClass('hidden'); 
            }
        }, function(error) { 
            if (error.responseJSON !== undefined) {
                modalAlert(error.responseJSON.info);
            }
        });    
    }); 
    // 点击分页地址
    $('#consumptionContaienr .pagination').on('click', 'li:not(.active)>a', function (e) {
        e.preventDefault();
        window.pageLink = $(this).data('value');
        consumptionTable();
    });
    // 删除记录
    $('#deleteModal').on('show.bs.modal', function(e) {
        var triggerId = $(e.relatedTarget);
        window.orderId = triggerId.data('id');
    });
    // 删除记录model点击
    $('#submitDetailDelete').on('click', function (e) {
        var param = {
                hotel: window.currentHotel,
                orderId: window.orderId
            },
            $me = $(this);
        ajaxRequest('/Home/Report/deleteOrderCost', param, 'post', function(data){
            consumptionTable();
            $('#deleteModal').modal('hide');
        }, null, $me);
    });    
});
